<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>MBTI测试后台管理系统</title>
    <!-- 使用可靠的Chart.js CDN -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.1.3/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.1.3/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.0/chart.umd.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.7.2/socket.io.min.js"></script>
    <style>
        :root {
            --primary: #4a6cf7;
            --primary-dark: #3a5ae8;
            --secondary: #6c757d;
            --success: #10b981;
            --info: #0ea5e9;
            --warning: #f59e0b;
            --danger: #ef4444;
            --light: #f8fafc;
            --dark: #0f172a;
            --sidebar-width: 280px;
            --header-height: 70px;
            --transition: all 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275);
        }

        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }

        body {
            font-family: 'Segoe UI', 'Microsoft YaHei', sans-serif;
            background-color: #f1f5f9;
            color: #334155;
            overflow-x: hidden;
            min-height: 100vh;
            display: flex;
        }

        /* 侧边栏样式 */
        .sidebar {
            width: var(--sidebar-width);
            background: linear-gradient(160deg, #0f172a, #1e293b);
            color: white;
            height: 100vh;
            position: fixed;
            top: 0;
            left: 0;
            z-index: 100;
            transition: var(--transition);
            box-shadow: 0 0 30px rgba(0, 0, 0, 0.1);
            overflow-y: auto;
        }

        .sidebar-header {
            padding: 20px;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .logo {
            width: 40px;
            height: 40px;
            background: linear-gradient(45deg, var(--primary), #8b5cf6);
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 20px;
        }

        .app-name {
            font-size: 1.2rem;
            font-weight: 700;
        }

        .sidebar-menu {
            padding: 20px 0;
        }

        .menu-title {
            font-size: 0.8rem;
            text-transform: uppercase;
            padding: 10px 25px;
            color: #94a3b8;
            letter-spacing: 1px;
        }

        .menu-item {
            padding: 12px 25px;
            display: flex;
            align-items: center;
            gap: 15px;
            cursor: pointer;
            transition: var(--transition);
            position: relative;
            overflow: hidden;
            font-size: 1.1rem;
        }

        .menu-item:hover, .menu-item.active {
            background: rgba(255, 255, 255, 0.1);
            color: white;
        }

        .menu-item.active::before {
            content: '';
            position: absolute;
            left: 0;
            top: 0;
            height: 100%;
            width: 4px;
            background: var(--primary);
        }

        .menu-item .badge {
            margin-left: auto;
            background: var(--primary);
            padding: 2px 8px;
            border-radius: 20px;
            font-size: 0.8rem;
        }

        /* 主内容区样式 */
        .main-content {
            flex: 1;
            margin-left: var(--sidebar-width);
            transition: var(--transition);
        }

        .header {
            height: var(--header-height);
            background: white;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
            display: flex;
            align-items: center;
            padding: 0 30px;
            position: sticky;
            top: 0;
            z-index: 99;
        }

        .toggle-sidebar {
            background: none;
            border: none;
            font-size: 1.5rem;
            color: var(--dark);
            cursor: pointer;
            display: none;
        }

        .header-right {
            margin-left: auto;
            display: flex;
            align-items: center;
            gap: 20px;
            position: relative;
        }

        .user-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: linear-gradient(45deg, var(--primary), #8b5cf6);
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: bold;
            cursor: pointer;
        }

        /* 内容区域 */
        .content {
            padding: 30px;
        }

        .page-title {
            font-size: 1.8rem;
            font-weight: 700;
            margin-bottom: 20px;
            color: var(--dark);
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .page-title .emoji-icon {
            background: linear-gradient(45deg, var(--primary), #8b5cf6);
            color: white;
            width: 50px;
            height: 50px;
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 24px;
        }

        .card {
            border: none;
            border-radius: 16px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.05);
            margin-bottom: 25px;
            transition: var(--transition);
            overflow: hidden;
            background: white;
        }

        .card:hover {
            transform: translateY(-5px);
            box-shadow: 0 15px 40px rgba(0, 0, 0, 0.1);
        }

        .card-header {
            background: white;
            padding: 20px;
            border-bottom: 1px solid #e2e8f0;
            font-weight: 600;
            font-size: 1.2rem;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .card-body {
            padding: 25px;
        }

        /* 统计卡片 */
        .stats-container {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }

        .stat-card {
            display: flex;
            align-items: center;
            padding: 20px;
            border-radius: 16px;
            background: white;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
            transition: var(--transition);
            cursor: pointer;
        }

        .stat-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
        }

        .stat-icon {
            width: 60px;
            height: 60px;
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 24px;
            margin-right: 15px;
        }

        .stat-info {
            flex: 1;
        }

        .stat-value {
            font-size: 1.8rem;
            font-weight: 700;
            margin-bottom: 5px;
        }

        .stat-title {
            color: #64748b;
            font-size: 0.95rem;
        }

        .trend {
            display: flex;
            align-items: center;
            font-size: 0.85rem;
            margin-top: 3px;
        }

        .trend.up {
            color: var(--success);
        }

        .trend.down {
            color: var(--danger);
        }

        /* 学生列表 */
        .student-item {
            padding: 15px;
            border-radius: 12px;
            background: white;
            margin-bottom: 15px;
            box-shadow: 0 4px 10px rgba(0, 0, 0, 0.03);
            transition: var(--transition);
            display: flex;
            align-items: center;
            border-left: 4px solid var(--primary);
        }

        .student-item:hover {
            transform: translateX(5px);
            box-shadow: 0 8px 20px rgba(0, 0, 0, 0.08);
        }

        .student-avatar {
            width: 45px;
            height: 45px;
            border-radius: 50%;
            background: linear-gradient(45deg, #8b5cf6, var(--primary));
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            font-size: 18px;
            margin-right: 15px;
            flex-shrink: 0;
        }

        .student-info {
            flex: 1;
        }

        .student-name {
            font-weight: 600;
            margin-bottom: 3px;
        }

        .student-id {
            font-size: 0.85rem;
            color: #64748b;
        }

        .student-status {
            font-size: 0.9rem;
            padding: 4px 12px;
            border-radius: 20px;
            font-weight: 500;
        }

        .status-tested {
            background: rgba(16, 185, 129, 0.15);
            color: var(--success);
        }

        .status-in-progress {
            background: rgba(59, 130, 246, 0.15);
            color: var(--info);
        }

        .status-not-tested {
            background: rgba(251, 191, 36, 0.15);
            color: var(--warning);
        }

        .student-progress {
            width: 120px;
            margin-left: 15px;
            flex-shrink: 0;
        }

        .progress {
            height: 8px;
            border-radius: 10px;
            background: #e2e8f0;
        }

        .progress-bar {
            border-radius: 10px;
            transition: width 0.5s ease;
        }

        .progress-text {
            font-size: 0.8rem;
            text-align: right;
            margin-top: 5px;
            color: #64748b;
        }

        /* 图表容器 */
        .chart-container {
            height: 300px;
            position: relative;
            margin-top: 15px;
        }

        /* 空状态样式 */
        .empty-state {
            text-align: center;
            padding: 40px 0;
            color: #64748b;
        }

        .empty-state .emoji-icon {
            font-size: 3.5rem;
            margin-bottom: 15px;
            display: block;
        }

        /* 添加学生表单 */
        .add-student-form {
            max-width: 600px;
            margin: 0 auto;
        }

        /* 动画效果 */
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(20px); }
            to { opacity: 1; transform: translateY(0); }
        }

        .animate-fadeIn {
            animation: fadeIn 0.5s ease forwards;
        }

        @keyframes highlightAdded {
            0% { background-color: #d4edda; transform: scale(0.95); opacity: 0; }
            50% { background-color: #d4edda; transform: scale(1.02); }
            100% { background-color: transparent; transform: scale(1); opacity: 1; }
        }

        @keyframes highlightRemoved {
            0% { opacity: 1; transform: translateX(0); }
            100% { opacity: 0; transform: translateX(100%); height: 0; padding: 0; margin: 0; border: none; }
        }

        @keyframes highlightUpdated {
            0% { background-color: #fff3cd; }
            100% { background-color: transparent; }
        }

        .student-item.added {
            animation: highlightAdded 1.5s;
        }

        .student-item.removed {
            animation: highlightRemoved 1s forwards;
        }

        .student-item.updated {
            animation: highlightUpdated 1.5s;
        }

        /* 通知样式 */
        .notification {
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 15px 20px;
            background: #4a6cf7;
            color: white;
            border-radius: 10px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
            z-index: 10000;
            animation: fadeIn 0.3s, fadeOut 0.3s 2.7s;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .notification.success {
            background: #10b981;
        }
        
        .notification.error {
            background: #ef4444;
        }
        
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(-20px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        @keyframes fadeOut {
            from { opacity: 1; transform: translateY(0); }
            to { opacity: 0; transform: translateY(-20px); }
        }

        /* 连接状态指示器 */
        .connection-status {
            display: flex;
            align-items: center;
            gap: 5px;
            font-size: 0.9rem;
            padding: 4px 8px;
            border-radius: 20px;
            background: rgba(59, 130, 246, 0.15);
            color: var(--info);
            cursor: pointer;
            transition: var(--transition);
            position: relative;
        }
        
        .connection-status:hover {
            background: rgba(59, 130, 246, 0.25);
        }
        
        .status-indicator {
            width: 10px;
            height: 10px;
            border-radius: 50%;
            display: inline-block;
        }
        
        .status-connected {
            background: var(--success);
        }
        
        .status-disconnected {
            background: var(--danger);
        }

        /* 监控面板 */
        .monitor-panel {
            position: absolute;
            top: 100%;
            right: 0;
            width: 300px;
            background: white;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
            border-radius: 0 0 16px 16px;
            padding: 20px;
            z-index: 1000;
            transform: translateY(-20px);
            opacity: 0;
            transition: all 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275);
            pointer-events: none;
        }
        
        .monitor-panel.open {
            transform: translateY(0);
            opacity: 1;
            pointer-events: all;
        }
        
        .monitor-item {
            display: flex;
            justify-content: space-between;
            padding: 10px 0;
            border-bottom: 1px solid #eee;
        }
        
        .monitor-label {
            color: #64748b;
            font-weight: 500;
        }
        
        .monitor-value {
            font-weight: 600;
        }
        
        .monitor-section {
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 1px solid #eee;
        }
        
        .monitor-section-title {
            font-weight: 600;
            margin-bottom: 15px;
            color: var(--dark);
            display: flex;
            align-items: center;
            gap: 10px;
        }

        /* 移动端优化 */
        @media (max-width: 992px) {
            .sidebar {
                transform: translateX(-100%);
            }
            
            .sidebar.open {
                transform: translateX(0);
            }
            
            .main-content {
                margin-left: 0;
            }
            
            .toggle-sidebar {
                display: block;
            }
            
            .content {
                padding: 20px;
            }
        }

        @media (max-width: 768px) {
            .stats-container {
                grid-template-columns: 1fr;
            }
            
            .student-item {
                flex-direction: column;
                align-items: flex-start;
            }
            
            .student-status {
                margin-top: 10px;
            }
            
            .student-progress {
                width: 100%;
                margin-top: 10px;
                margin-left: 0;
            }
        }

        /* 选项卡样式 */
        .tab-content {
            padding: 20px 0;
        }

        .tab-pane {
            display: none;
        }

        .tab-pane.active {
            display: block;
        }
        
        /* 表单样式 */
        .form-control {
            padding: 12px 15px;
            border-radius: 10px;
            border: 1px solid #ddd;
            font-size: 16px;
            transition: var(--transition);
        }
        
        .form-control:focus {
            border-color: var(--primary);
            box-shadow: 0 0 0 3px rgba(74, 108, 247, 0.2);
        }
        
        .btn {
            padding: 12px 20px;
            border-radius: 10px;
            font-weight: 600;
            cursor: pointer;
            transition: var(--transition);
            border: none;
        }
        
        .btn-primary {
            background: var(--primary);
            color: white;
        }
        
        .btn-primary:hover {
            background: var(--primary-dark);
        }
        
        .btn-sm {
            padding: 8px 15px;
            font-size: 0.9rem;
        }
        
        .btn-danger {
            background: var(--danger);
            color: white;
        }
        
        .btn-danger:hover {
            background: #dc2626;
        }
        
        .input-group {
            display: flex;
        }
        
        .input-group .form-control {
            border-radius: 10px 0 0 10px;
            flex: 1;
        }
        
        .input-group .btn {
            border-radius: 0 10px 10px 0;
        }
        
        /* 筛选标签激活状态 */
        .filter-btn.active {
            background-color: var(--primary);
            color: white;
            border-color: var(--primary);
        }
    </style>
</head>
<body>
    <!-- 侧边导航栏 -->
    <div class="sidebar">
        <div class="sidebar-header">
            <div class="logo">🧠</div>
            <div class="app-name">MBTI测试管理</div>
        </div>
        
        <div class="sidebar-menu">
            <div class="menu-title">主要导航</div>
            <div class="menu-item active" data-tab="dashboard">
                <span class="emoji">📊</span>
                <span>控制面板</span>
            </div>
            <div class="menu-item" data-tab="students">
                <span class="emoji">👨‍🎓</span>
                <span>学生管理</span>
                <span class="badge" id="student-count">0</span>
            </div>
            <div class="menu-item" data-tab="results">
                <span class="emoji">📝</span>
                <span>测试结果</span>
            </div>
            
            <div class="menu-title">系统设置</div>
            <div class="menu-item" data-tab="settings">
                <span class="emoji">⚙️</span>
                <span>系统设置</span>
            </div>
            <div class="menu-item" data-tab="analytics">
                <span class="emoji">📈</span>
                <span>数据分析</span>
            </div>
        </div>
    </div>

    <!-- 主内容区 -->
    <div class="main-content">
        <!-- 顶部导航 -->
        <div class="header">
            <button class="toggle-sidebar">
                ☰
            </button>
            
            <div class="header-right">
                <div class="connection-status" id="connection-status">
                    <span class="status-indicator status-disconnected" id="status-indicator"></span>
                    <span>连接中...</span>
                </div>
                
                <div class="user-avatar">
                    <span>A</span>
                </div>
                
                <!-- 监控面板 -->
                <div class="monitor-panel" id="monitor-panel">
                    <div class="monitor-section">
                        <div class="monitor-section-title">
                            <span>🔌</span>
                            系统状态
                        </div>
                        <div class="monitor-item">
                            <span class="monitor-label">服务器状态</span>
                            <span class="monitor-value" id="server-status">运行中</span>
                        </div>
                        <div class="monitor-item">
                            <span class="monitor-label">在线时间</span>
                            <span class="monitor-value" id="uptime">0 天</span>
                        </div>
                        <div class="monitor-item">
                            <span class="monitor-label">数据库连接</span>
                            <span class="monitor-value" id="db-status">正常</span>
                        </div>
                    </div>
                    
                    <div class="monitor-section">
                        <div class="monitor-section-title">
                            <span>📊</span>
                            资源使用
                        </div>
                        <div class="monitor-item">
                            <span class="monitor-label">内存使用</span>
                            <span class="monitor-value" id="memory-usage">0 MB</span>
                        </div>
                        <div class="monitor-item">
                            <span class="monitor-label">连接数</span>
                            <span class="monitor-value" id="connection-count">0</span>
                        </div>
                        <div class="monitor-item">
                            <span class="monitor-label">最后更新</span>
                            <span class="monitor-value" id="last-update">刚刚</span>
                        </div>
                    </div>
                    
                    <div class="monitor-section">
                        <div class="monitor-section-title">
                            <span>ℹ️</span>
                            系统信息
                        </div>
                        <div class="monitor-item">
                            <span class="monitor-label">系统版本</span>
                            <span class="monitor-value">v1.0.0</span>
                        </div>
                        <div class="monitor-item">
                            <span class="monitor-label">学生总数</span>
                            <span class="monitor-value" id="total-students">0</span>
                        </div>
                        <div class="monitor-item">
                            <span class="monitor-label">测试总数</span>
                            <span class="monitor-value" id="total-tests">0</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 内容区域 -->
        <div class="content">
            <!-- 控制面板 -->
            <div class="tab-pane active" id="dashboard">
                <div class="page-title">
                    <div class="emoji-icon">📊</div>
                    <span>控制面板</span>
                </div>
                
                <!-- 统计卡片 -->
                <div class="stats-container">
                    <div class="stat-card animate-fadeIn" style="animation-delay: 0.1s" data-scroll="tested-students">
                        <div class="stat-icon" style="background: rgba(16, 185, 129, 0.15); color: var(--success);">
                            ✅
                        </div>
                        <div class="stat-info">
                            <div class="stat-value" id="tested-count">0</div>
                            <div class="stat-title">已测试学生</div>
                            <div class="trend up">
                                ↑ <span id="tested-trend">0%</span> 增长
                            </div>
                        </div>
                    </div>
                    
                    <div class="stat-card animate-fadeIn" style="animation-delay: 0.2s" data-scroll="in-progress-students">
                        <div class="stat-icon" style="background: rgba(59, 130, 246, 0.15); color: var(--info);">
                            🔄
                        </div>
                        <div class="stat-info">
                            <div class="stat-value" id="in-progress-count">0</div>
                            <div class="stat-title">测试中</div>
                            <div class="trend up">
                                ↑ <span id="in-progress-trend">0%</span> 增长
                            </div>
                        </div>
                    </div>
                    
                    <div class="stat-card animate-fadeIn" style="animation-delay: 0.3s" data-scroll="not-tested-students">
                        <div class="stat-icon" style="background: rgba(251, 191, 36, 0.15); color: var(--warning);">
                            ⏳
                        </div>
                        <div class="stat-info">
                            <div class="stat-value" id="not-tested-count">0</div>
                            <div class="stat-title">未开始测试</div>
                            <div class="trend down">
                                ↓ <span id="not-tested-trend">0%</span> 减少
                            </div>
                        </div>
                    </div>
                    
                    <div class="stat-card animate-fadeIn" style="animation-delay: 0.4s" data-scroll="mbti-types">
                        <div class="stat-icon" style="background: rgba(139, 92, 246, 0.15); color: #8b5cf6;">
                            📋
                        </div>
                        <div class="stat-info">
                            <div class="stat-value" id="mbti-types-count">0</div>
                            <div class="stat-title">人格类型</div>
                            <div class="trend up">
                                ↑ <span id="mbti-trend">0%</span> 增长
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- 图表和列表 -->
                <div class="row">
                    <div class="col-lg-8">
                        <div class="card">
                            <div class="card-header">
                                📈 测试进度分布
                            </div>
                            <div class="card-body">
                                <div class="chart-container">
                                    <canvas id="progressChart"></canvas>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="col-lg-4">
                        <div class="card">
                            <div class="card-header">
                                👥 最近活动
                            </div>
                            <div class="card-body">
                                <div class="student-list" id="recent-students">
                                    <div class="empty-state">
                                        <span class="emoji-icon">⏳</span>
                                        <div>加载中...</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- 人格类型分布 -->
                <div class="card" id="mbti-types">
                    <div class="card-header">
                        📊 人格类型分布
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-lg-7">
                                <div class="chart-container">
                                    <canvas id="mbtiChart"></canvas>
                                </div>
                            </div>
                            <div class="col-lg-5">
                                <div class="table-responsive">
                                    <table class="table table-hover" id="mbti-table">
                                        <thead>
                                            <tr>
                                                <th>人格类型</th>
                                                <th>学生数量</th>
                                                <th>占比</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <!-- 动态加载人格类型数据 -->
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- 学生管理 -->
            <div class="tab-pane" id="students">
                <div class="page-title">
                    <div class="emoji-icon">👨‍🎓</div>
                    <span>学生管理</span>
                </div>
                
                <div class="card">
                    <div class="card-header">
                        📋 学生列表
                        <button class="btn btn-sm btn-primary" id="refresh-students" style="float: right;">
                            🔄 刷新
                        </button>
                    </div>
                    <div class="card-body">
                        <div class="d-flex gap-2 mb-4">
                            <button class="btn btn-outline-primary filter-btn active" data-filter="all">全部</button>
                            <button class="btn btn-outline-success filter-btn" data-filter="tested">已测试</button>
                            <button class="btn btn-outline-info filter-btn" data-filter="in-progress">测试中</button>
                            <button class="btn btn-outline-warning filter-btn" data-filter="not-tested">未开始</button>
                        </div>
                        
                        <div class="student-list">
                            <div id="tested-students" class="student-section">
                                <h4 class="mb-3">✅ 已测试学生 <span class="badge bg-success" id="tested-count-badge">0</span></h4>
                                <div id="tested-students-list"></div>
                            </div>
                            
                            <div id="in-progress-students" class="student-section mt-5">
                                <h4 class="mb-3">🔄 测试中学生 <span class="badge bg-info" id="in-progress-count-badge">0</span></h4>
                                <div id="in-progress-students-list"></div>
                            </div>
                            
                            <div id="not-tested-students" class="student-section mt-5">
                                <h4 class="mb-3">⏳ 未开始学生 <span class="badge bg-warning" id="not-tested-count-badge">0</span></h4>
                                <div id="not-tested-students-list"></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- 测试结果 -->
            <div class="tab-pane" id="results">
                <div class="page-title">
                    <div class="emoji-icon">📝</div>
                    <span>测试结果分析</span>
                </div>
                
                <div class="card">
                    <div class="card-header">
                        📊 维度分布
                    </div>
                    <div class="card-body">
                        <div class="chart-container">
                            <canvas id="dimensionChart"></canvas>
                        </div>
                    </div>
                </div>
                
                <div class="card">
                    <div class="card-header">
                        📋 详细结果
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-hover">
                                <thead>
                                    <tr>
                                        <th>学号</th>
                                        <th>姓名</th>
                                        <th>人格类型</th>
                                        <th>测试时间</th>
                                        <th>测试题目数</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody id="results-table">
                                    <!-- 动态加载测试结果 -->
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- 系统设置 -->
            <div class="tab-pane" id="settings">
                <div class="page-title">
                    <div class="emoji-icon">⚙️</div>
                    <span>系统设置</span>
                </div>
                
                <div class="card">
                    <div class="card-header">
                        🔒 管理员设置
                    </div>
                    <div class="card-body">
                        <form class="add-student-form" id="admin-settings-form">
                            <div class="mb-3">
                                <label class="form-label">管理员用户名</label>
                                <input type="text" class="form-control" value="admin" readonly>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">当前密码</label>
                                <input type="password" class="form-control" name="current_password" placeholder="输入当前密码" required>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">新密码</label>
                                <input type="password" class="form-control" name="new_password" placeholder="输入新密码" required>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">确认密码</label>
                                <input type="password" class="form-control" name="confirm_password" placeholder="确认新密码" required>
                            </div>
                            <div class="d-grid">
                                <button type="submit" class="btn btn-primary">
                                    🔑 更新密码
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
                
                <div class="card mt-4">
                    <div class="card-header">
                        🌐 系统参数
                    </div>
                    <div class="card-body">
                        <form class="add-student-form" id="system-settings-form">
                            <div class="mb-3">
                                <label class="form-label">系统名称</label>
                                <input type="text" class="form-control" name="system_name" value="MBTI测试系统">
                            </div>
                            <div class="mb-3">
                                <label class="form-label">最大学生数</label>
                                <input type="number" class="form-control" name="max_students" value="1000">
                            </div>
                            <div class="mb-3">
                                <label class="form-label">数据保留时间</label>
                                <select class="form-control" name="data_retention">
                                    <option value="30">30天</option>
                                    <option value="90" selected>90天</option>
                                    <option value="180">180天</option>
                                    <option value="0">永久</option>
                                </select>
                            </div>
                            <div class="d-grid">
                                <button type="submit" class="btn btn-primary">
                                    💾 保存设置
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
            
            <!-- 数据分析 -->
            <div class="tab-pane" id="analytics">
                <div class="page-title">
                    <div class="emoji-icon">📈</div>
                    <span>数据分析</span>
                </div>
                
                <div class="card">
                    <div class="card-header">
                        📊 测试趋势分析
                    </div>
                    <div class="card-body">
                        <div class="chart-container">
                            <canvas id="trendChart"></canvas>
                        </div>
                    </div>
                </div>
                
                <div class="card mt-4">
                    <div class="card-header">
                        📋 维度分布统计
                    </div>
                    <div class="card-body">
                        <div class="chart-container">
                            <canvas id="dimensionDistributionChart"></canvas>
                        </div>
                    </div>
                </div>
                
                <div class="card mt-4">
                    <div class="card-header">
                        📋 测试题目分析
                    </div>
                    <div class="card-body">
                        <div class="chart-container">
                            <canvas id="questionAnalysisChart"></canvas>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        // 存储图表实例
        let progressChart = null;
        let mbtiChart = null;
        let dimensionChart = null;
        let trendChart = null;
        let dimensionDistributionChart = null;
        let questionAnalysisChart = null;
        let currentTab = 'dashboard'; // 跟踪当前激活的标签页
        let socket = null;
        let connectionAttempts = 0;
        const MAX_RETRIES = 5;
        let systemSettings = {
            system_name: "MBTI测试系统",
            max_students: 1000,
            data_retention: 90
        };

        // 初始化数据
        let studentsData = {
            tested: [],
            in_progress: [],
            not_tested: [],
            mbtiTypes: {},
            dimensionStats: null,
            testResults: [],
            testTrends: []
        };

        // 初始化侧边栏切换
        document.querySelector('.toggle-sidebar')?.addEventListener('click', function() {
            document.querySelector('.sidebar').classList.toggle('open');
        });

        // 菜单项点击事件
        document.querySelectorAll('.menu-item').forEach(item => {
            item.addEventListener('click', function() {
                // 移除所有active类
                document.querySelectorAll('.menu-item').forEach(el => {
                    el.classList.remove('active');
                });
                
                // 为当前项添加active类
                this.classList.add('active');
                
                // 切换到对应标签页
                const tab = this.getAttribute('data-tab');
                currentTab = tab;
                document.querySelectorAll('.tab-pane').forEach(pane => {
                    pane.classList.remove('active');
                });
                document.getElementById(tab).classList.add('active');
                
                // 根据标签页更新内容
                switch(tab) {
                    case 'dashboard':
                        updateDashboard();
                        break;
                    case 'students':
                        updateAllStudents();
                        break;
                    case 'results':
                        updateResults();
                        break;
                    case 'analytics':
                        updateAnalytics();
                        break;
                }
            });
        });

        // 设置Socket.IO连接
        function setupSocketConnection() {
            if (connectionAttempts >= MAX_RETRIES) {
                showNotification('无法连接服务器，请检查网络或服务器状态', 'error');
                updateConnectionStatus('disconnected');
                return;
            }
            
            connectionAttempts++;
            updateConnectionStatus('connecting');
            
            // 尝试连接
            socket = io('/admin', {
                reconnection: true,
                reconnectionAttempts: MAX_RETRIES,
                reconnectionDelay: 3000,
                reconnectionDelayMax: 10000,
                timeout: 20000
            });

            socket.on('connect', () => {
                console.log('Connected to admin namespace');
                updateConnectionStatus('connected');
                fetchInitialData();
            });

            socket.on('student_update', (data) => {
                console.log('Received student update');
                studentsData = {
                    ...studentsData,
                    ...data
                };
                updateUI();
            });

            socket.on('disconnect', (reason) => {
                console.log('Disconnected:', reason);
                updateConnectionStatus('disconnected');
                if (reason === 'io server disconnect') {
                    // 服务器主动断开，尝试重新连接
                    socket.connect();
                }
            });

            socket.on('connect_error', (error) => {
                console.error('Connection Error:', error);
                updateConnectionStatus('disconnected');
                // 尝试重新连接
                setTimeout(setupSocketConnection, 3000);
            });
        }

        // 更新连接状态
        function updateConnectionStatus(status) {
            const statusIndicator = document.getElementById('status-indicator');
            const statusText = document.getElementById('connection-status').querySelector('span:last-child');
            
            if (!statusIndicator) return;
            
            statusIndicator.classList.remove('status-connected', 'status-disconnected');
            
            switch(status) {
                case 'connected':
                    statusIndicator.classList.add('status-connected');
                    statusText.textContent = '已连接';
                    break;
                case 'connecting':
                    statusIndicator.classList.add('status-disconnected');
                    statusText.textContent = '连接中...';
                    break;
                case 'disconnected':
                    statusIndicator.classList.add('status-disconnected');
                    statusText.textContent = '连接断开';
                    break;
            }
        }

        // 获取初始数据
        async function fetchInitialData() {
            try {
                // 获取学生数据
                const studentResponse = await fetch('/api/admin/students');
                if (!studentResponse.ok) throw new Error('网络响应错误');
                const studentData = await studentResponse.json();
                
                // 获取测试结果数据
                const resultsResponse = await fetch('/api/admin/results');
                if (!resultsResponse.ok) throw new Error('网络响应错误');
                const resultsData = await resultsResponse.json();
                
                // 获取系统设置
                const settingsResponse = await fetch('/api/admin/settings');
                if (settingsResponse.ok) {
                    const settingsData = await settingsResponse.json();
                    systemSettings = settingsData;
                    applySystemSettings();
                }
                
                // 合并数据
                studentsData = {
                    ...studentData,
                    mbtiTypes: resultsData.mbti_types || {},
                    dimensionStats: resultsData.dimension_stats || null,
                    testResults: resultsData.results || [],
                    testTrends: resultsData.test_trends || []
                };
                
                // 获取系统状态
                await updateSystemStatus();
                
                updateUI();
            } catch (error) {
                console.error('获取初始数据失败:', error);
                showNotification(`数据加载失败: ${error.message}`, 'error');
            }
        }
        
        // 更新系统状态
        async function updateSystemStatus() {
            try {
                const response = await fetch('/api/admin/system_status');
                if (!response.ok) throw new Error('获取系统状态失败');
                const statusData = await response.json();
                
                // 更新监控面板
                safeUpdateElement('server-status', statusData.server_status);
                safeUpdateElement('uptime', statusData.uptime);
                safeUpdateElement('memory-usage', statusData.memory_usage);
                safeUpdateElement('connection-count', statusData.connection_count);
                safeUpdateElement('last-update', statusData.last_update);
                
                // 更新数据库状态（假设正常）
                safeUpdateElement('db-status', '正常');
            } catch (error) {
                console.error('获取系统状态失败:', error);
                safeUpdateElement('server-status', '异常');
                safeUpdateElement('db-status', '断开');
            }
        }

        // 应用系统设置
        function applySystemSettings() {
            // 更新系统名称
            document.querySelector('title').textContent = systemSettings.system_name + " - 后台管理系统";
            
            // 更新表单值
            if (document.getElementById('system-settings-form')) {
                document.getElementById('system-settings-form').querySelector('[name="system_name"]').value = systemSettings.system_name;
                document.getElementById('system-settings-form').querySelector('[name="max_students"]').value = systemSettings.max_students;
                document.getElementById('system-settings-form').querySelector('[name="data_retention"]').value = systemSettings.data_retention;
            }
        }

        // 更新UI
        function updateUI() {
            // 只更新当前激活标签页的内容
            switch(currentTab) {
                case 'dashboard':
                    updateDashboard();
                    break;
                case 'students':
                    updateAllStudents();
                    break;
                case 'results':
                    updateResults();
                    break;
                case 'analytics':
                    updateAnalytics();
                    break;
            }
            
            // 统计数据在所有页面都需要更新
            updateStatistics();
            updateMonitorPanel();
        }

        // 更新监控面板
        function updateMonitorPanel() {
            // 更新学生总数
            const totalStudents = studentsData.tested.length + 
                                 studentsData.in_progress.length + 
                                 studentsData.not_tested.length;
            safeUpdateElement('total-students', totalStudents);
            
            // 更新测试总数
            safeUpdateElement('total-tests', studentsData.tested.length);
        }
        
        // 更新仪表盘
        function updateDashboard() {
            updateRecentStudents();
            updateCharts();
        }

        // 更新结果页面
        function updateResults() {
            updateResultsTable();
            updateDimensionChart();
        }

        // 更新分析页面
        function updateAnalytics() {
            updateTrendChart();
            updateDimensionDistributionChart();
            updateQuestionAnalysisChart();
        }

        // 更新统计信息
        function updateStatistics() {
            const testedCount = studentsData.tested.length;
            const inProgressCount = studentsData.in_progress.length;
            const notTestedCount = studentsData.not_tested.length;
            const mbtiTypesCount = Object.keys(studentsData.mbtiTypes || {}).length;
            const totalStudents = testedCount + inProgressCount + notTestedCount;
            
            // 安全更新元素
            safeUpdateElement('tested-count', testedCount);
            safeUpdateElement('in-progress-count', inProgressCount);
            safeUpdateElement('not-tested-count', notTestedCount);
            safeUpdateElement('mbti-types-count', mbtiTypesCount);
            safeUpdateElement('student-count', totalStudents);
            
            // 更新学生管理页面的计数徽章
            safeUpdateElement('tested-count-badge', testedCount);
            safeUpdateElement('in-progress-count-badge', inProgressCount);
            safeUpdateElement('not-tested-count-badge', notTestedCount);
        }

        // 安全更新元素内容
        function safeUpdateElement(id, content) {
            const element = document.getElementById(id);
            if (element) {
                element.textContent = content;
            }
        }

        // 更新最近活动学生
        function updateRecentStudents() {
            const container = document.getElementById('recent-students');
            if (!container) return;
            
            container.innerHTML = '';
            
            // 获取最近5个活动学生
            const recentStudents = [
                ...studentsData.tested.slice(0, 2),
                ...studentsData.in_progress.slice(0, 2),
                ...studentsData.not_tested.slice(0, 1)
            ];
            
            if (recentStudents.length === 0) {
                container.innerHTML = `
                    <div class="empty-state">
                        <span class="emoji-icon">👥</span>
                        <div>暂无学生活动</div>
                    </div>
                `;
                return;
            }
            
            recentStudents.forEach(student => {
                const studentEl = createStudentElement(student);
                // 添加点击事件跳转到学生详情
                studentEl.addEventListener('click', function() {
                    window.location.href = `/result/${student.student_id}`;
                });
                container.appendChild(studentEl);
            });
        }

        // 创建学生元素
        function createStudentElement(student) {
            const studentEl = document.createElement('div');
            studentEl.className = 'student-item';
            
            // 学生头像
            const firstChar = student.name.charAt(0);
            
            // 学生状态
            let statusClass = 'status-not-tested';
            let statusText = '未开始';
            let progressHtml = '';
            
            if (student.has_tested) {
                statusClass = 'status-tested';
                statusText = '已完成';
            } else if (student.current_progress) {
                statusClass = 'status-in-progress';
                statusText = '测试中';
                const progress = Math.round((student.current_progress / student.test_length) * 100);
                progressHtml = `
                    <div class="student-progress">
                        <div class="progress">
                            <div class="progress-bar" style="width: ${progress}%"></div>
                        </div>
                        <div class="progress-text">${progress}% 完成 (${student.current_progress}/${student.test_length})</div>
                    </div>
                `;
            }
            
            studentEl.innerHTML = `
                <div class="student-avatar">${firstChar}</div>
                <div class="student-info">
                    <div class="student-name">${student.name}</div>
                    <div class="student-id">${student.student_id}</div>
                </div>
                <div class="student-status ${statusClass}">${statusText}</div>
                ${progressHtml}
            `;
            
            return studentEl;
        }

        // 更新所有学生列表
        function updateAllStudents() {
            updateStudentList('tested-students-list', studentsData.tested);
            updateStudentList('in-progress-students-list', studentsData.in_progress);
            updateStudentList('not-tested-students-list', studentsData.not_tested);
        }

        // 更新学生列表
        function updateStudentList(containerId, students) {
            const container = document.getElementById(containerId);
            if (!container) return;
            
            container.innerHTML = '';
            
            if (students.length === 0) {
                container.innerHTML = `<div class="empty-state py-3">
                    <img src="/static/images/暂无学生数据.jpg" alt="用户图标" style="display: inline-block; width: 10em; height: 10em; vertical-align: middle;">
                    <div>暂无学生</div>
                </div>`;
                return;
            }
            
            students.forEach(student => {
                const studentEl = createStudentElement(student);
                
                // 添加删除按钮
                const deleteBtn = document.createElement('button');
                deleteBtn.className = 'btn btn-sm btn-danger delete-student';
                deleteBtn.setAttribute('data-id', student.student_id);
                deleteBtn.innerHTML = '🗑️ 删除';
                studentEl.appendChild(deleteBtn);
                
                container.appendChild(studentEl);
            });
        }

        // 更新测试结果表格
        function updateResultsTable() {
            const container = document.getElementById('results-table');
            if (!container) return;
            
            container.innerHTML = '';
            
            if (!studentsData.testResults || studentsData.testResults.length === 0) {
                container.innerHTML = `
                    <tr>
                        <td colspan="6" class="text-center py-4">
                            <div class="empty-state">
                                <span class="emoji-icon">📝</span>
                                <div>暂无测试结果</div>
                            </div>
                        </td>
                    </tr>
                `;
                return;
            }
            
            studentsData.testResults.forEach(result => {
                // 转换时间戳为可读格式
                const testDate = new Date().toLocaleString(); // 使用当前时间代替
                
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td>${result.student_id}</td>
                    <td>${result.name}</td>
                    <td>${result.mbti}</td>
                    <td>${testDate}</td>
                    <td>${result.test_length}</td>
                    <td>
                        <a href="/result/${result.student_id}" class="btn btn-sm btn-primary">
                            查看详情
                        </a>
                    </td>
                `;
                container.appendChild(row);
            });
        }

        // 更新图表
        function updateCharts() {
            // 确保Chart.js已加载
            if (typeof Chart === 'undefined') {
                console.error('Chart.js未加载');
                showNotification('图表库加载失败，请刷新页面重试', 'error');
                return;
            }
            
            // 测试进度图表
            updateProgressChart();
            
            // MBTI分布饼图
            updateMbtiChart();
            
            // 维度分布图
            updateDimensionChart();
            
            // 更新MBTI表格
            updateMbtiTable();
        }
        
        // 更新趋势图表
        function updateTrendChart() {
            const trendCtx = document.getElementById('trendChart')?.getContext('2d');
            if (!trendCtx || !studentsData.testTrends) return;
            
            if (trendChart) {
                trendChart.destroy();
            }
            
            // 准备图表数据
            const labels = studentsData.testTrends.map(trend => trend.date);
            const testedData = studentsData.testTrends.map(trend => trend.tested);
            const inProgressData = studentsData.testTrends.map(trend => trend.in_progress);
            
            trendChart = new Chart(trendCtx, {
                type: 'line',
                data: {
                    labels: labels,
                    datasets: [
                        {
                            label: '已测试学生',
                            data: testedData,
                            borderColor: '#10b981',
                            backgroundColor: 'rgba(16, 185, 129, 0.1)',
                            tension: 0.3,
                            fill: true
                        },
                        {
                            label: '测试中学生',
                            data: inProgressData,
                            borderColor: '#0ea5e9',
                            backgroundColor: 'rgba(59, 130, 246, 0.1)',
                            tension: 0.3,
                            fill: true
                        }
                    ]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        y: {
                            beginAtZero: true,
                            grid: {
                                color: 'rgba(0, 0, 0, 0.05)'
                            }
                        },
                        x: {
                            grid: {
                                display: false
                            }
                        }
                    }
                }
            });
        }
        
        // 更新维度分布图表
        function updateDimensionDistributionChart() {
            const dimensionCtx = document.getElementById('dimensionDistributionChart')?.getContext('2d');
            if (!dimensionCtx || !studentsData.dimensionStats) return;
            
            if (dimensionDistributionChart) {
                dimensionDistributionChart.destroy();
            }
            
            const stats = studentsData.dimensionStats;
            dimensionDistributionChart = new Chart(dimensionCtx, {
                type: 'bar',
                data: {
                    labels: ['E', 'I', 'S', 'N', 'T', 'F', 'J', 'P'],
                    datasets: [{
                        label: '平均分数',
                        data: [
                            stats['E-I'].E, stats['E-I'].I,
                            stats['S-N'].S, stats['S-N'].N,
                            stats['T-F'].T, stats['T-F'].F,
                            stats['J-P'].J, stats['J-P'].P
                        ],
                        backgroundColor: [
                            '#0ea5e9', '#6366f1',
                            '#0ea5e9', '#6366f1',
                            '#0ea5e9', '#6366f1',
                            '#0ea5e9', '#6366f1'
                        ],
                        borderColor: [
                            '#0c89c7', '#4f46e5',
                            '#0c89c7', '#4f46e5',
                            '#0c89c7', '#4f46e5',
                            '#0c89c7', '#4f46e5'
                        ],
                        borderWidth: 1
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        y: {
                            beginAtZero: true,
                            grid: {
                                color: 'rgba(0, 0, 0, 0.05)'
                            }
                        }
                    }
                }
            });
        }
        
        // 更新题目分析图表
        function updateQuestionAnalysisChart() {
            const questionCtx = document.getElementById('questionAnalysisChart')?.getContext('2d');
            if (!questionCtx) return;
            
            if (questionAnalysisChart) {
                questionAnalysisChart.destroy();
            }
            
            // 模拟数据 - 实际应用中应从后端获取
            const questionData = {
                labels: ['1-10', '11-20', '21-30', '31-40', '41-50', '51-60', '61-70', '71-80', '81-90', '91-100'],
                datasets: [{
                    label: '平均完成时间(秒)',
                    data: [12, 15, 18, 14, 16, 20, 22, 19, 17, 15],
                    backgroundColor: 'rgba(139, 92, 246, 0.2)',
                    borderColor: 'rgba(139, 92, 246, 1)',
                    borderWidth: 2,
                    tension: 0.3
                }]
            };
            
            questionAnalysisChart = new Chart(questionCtx, {
                type: 'line',
                data: questionData,
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        y: {
                            beginAtZero: true,
                            grid: {
                                color: 'rgba(0, 0, 0, 0.05)'
                            }
                        }
                    }
                }
            });
        }
        
        // 更新进度图表
        function updateProgressChart() {
            const progressCtx = document.getElementById('progressChart')?.getContext('2d');
            if (!progressCtx) return;
            
            if (progressChart) {
                progressChart.destroy();
            }
            
            progressChart = new Chart(progressCtx, {
                type: 'bar',
                data: {
                    labels: ['已测试', '测试中', '未开始'],
                    datasets: [{
                        label: '学生数量',
                        data: [
                            studentsData.tested.length,
                            studentsData.in_progress.length,
                            studentsData.not_tested.length
                        ],
                        backgroundColor: [
                            'rgba(16, 185, 129, 0.7)',
                            'rgba(59, 130, 246, 0.7)',
                            'rgba(251, 191, 36, 0.7)'
                        ],
                        borderColor: [
                            'rgba(16, 185, 129, 1)',
                            'rgba(59, 130, 246, 1)',
                            'rgba(251, 191, 36, 1)'
                        ],
                        borderWidth: 1
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        y: {
                            beginAtZero: true,
                            grid: {
                                color: 'rgba(0, 0, 0, 0.05)'
                            }
                        },
                        x: {
                            grid: {
                                display: false
                            }
                        }
                    },
                    plugins: {
                        legend: {
                            display: false
                        }
                    }
                }
            });
        }
        
        // 更新MBTI图表
        function updateMbtiChart() {
            const mbtiCtx = document.getElementById('mbtiChart')?.getContext('2d');
            if (!mbtiCtx) return;
            
            if (mbtiChart) {
                mbtiChart.destroy();
            }
            
            const mbtiLabels = Object.keys(studentsData.mbtiTypes || {});
            const mbtiData = mbtiLabels.map(type => studentsData.mbtiTypes[type]);
            
            mbtiChart = new Chart(mbtiCtx, {
                type: 'doughnut',
                data: {
                    labels: mbtiLabels,
                    datasets: [{
                        data: mbtiData,
                        backgroundColor: [
                            'rgba(139, 92, 246, 0.7)',
                            'rgba(16, 185, 129, 0.7)',
                            'rgba(59, 130, 246, 0.7)',
                            'rgba(245, 158, 11, 0.7)',
                            'rgba(239, 68, 68, 0.7)',
                            'rgba(148, 163, 184, 0.7)'
                        ],
                        borderColor: [
                            'rgba(139, 92, 246, 1)',
                            'rgba(16, 185, 129, 1)',
                            'rgba(59, 130, 246, 1)',
                            'rgba(245, 158, 11, 1)',
                            'rgba(239, 68, 68, 1)',
                            'rgba(148, 163, 184, 1)'
                        ],
                        borderWidth: 1
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'right',
                        },
                        tooltip: {
                            callbacks: {
                                label: function(context) {
                                    const label = context.label || '';
                                    const value = context.raw || 0;
                                    const total = context.chart.getDatasetMeta(0).total;
                                    const percentage = Math.round((value / total) * 100);
                                    return `${label}: ${value} (${percentage}%)`;
                                }
                            }
                        }
                    }
                }
            });
        }
        
        // 更新维度图表
        function updateDimensionChart() {
            const dimensionCtx = document.getElementById('dimensionChart')?.getContext('2d');
            if (!dimensionCtx || !studentsData.dimensionStats) return;
            
            if (dimensionChart) {
                dimensionChart.destroy();
            }
            
            const stats = studentsData.dimensionStats;
            dimensionChart = new Chart(dimensionCtx, {
                type: 'radar',
                data: {
                    labels: ['外向(E)', '内向(I)', '实感(S)', '直觉(N)', '思考(T)', '情感(F)', '判断(J)', '感知(P)'],
                    datasets: [{
                        label: '维度分数',
                        data: [
                            stats['E-I'].E,
                            stats['E-I'].I,
                            stats['S-N'].S,
                            stats['S-N'].N,
                            stats['T-F'].T,
                            stats['T-F'].F,
                            stats['J-P'].J,
                            stats['J-P'].P
                        ],
                        backgroundColor: 'rgba(74, 108, 247, 0.2)',
                        borderColor: 'rgba(74, 108, 247, 1)',
                        pointBackgroundColor: 'rgba(74, 108, 247, 1)',
                        pointBorderColor: '#fff',
                        pointHoverBackgroundColor: '#fff',
                        pointHoverBorderColor: 'rgba(74, 108, 247, 1)'
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        r: {
                            angleLines: {
                                display: true
                            },
                            suggestedMin: 0
                        }
                    }
                }
            });
        }
        
        // 更新MBTI表格
        function updateMbtiTable() {
            const mbtiTable = document.getElementById('mbti-table');
            if (!mbtiTable) return;
            
            const tbody = mbtiTable.querySelector('tbody');
            if (!tbody) return;
            
            tbody.innerHTML = '';
            
            const mbtiLabels = Object.keys(studentsData.mbtiTypes || {});
            let totalStudents = 0;
            mbtiLabels.forEach(type => {
                totalStudents += studentsData.mbtiTypes[type];
            });
            
            mbtiLabels.forEach(type => {
                const count = studentsData.mbtiTypes[type];
                const percentage = totalStudents > 0 ? Math.round((count / totalStudents) * 100) : 0;
                
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td>${type}</td>
                    <td>${count}</td>
                    <td>${percentage}%</td>
                `;
                tbody.appendChild(row);
            });
        }

        // 显示通知
        function showNotification(message, type = 'info') {
            // 移除现有通知
            document.querySelectorAll('.notification').forEach(n => n.remove());
            
            // 创建通知元素
            const notification = document.createElement('div');
            notification.className = `notification ${type === 'success' ? 'success' : type === 'error' ? 'error' : ''}`;
            
            // 设置内容
            notification.innerHTML = `
                <span style="font-size: 1.2rem;">${type === 'success' ? '✅' : type === 'error' ? '❌' : 'ℹ️'}</span>
                <span>${message}</span>
            `;
            
            document.body.appendChild(notification);
            
            // 5秒后移除通知
            setTimeout(() => {
                notification.remove();
            }, 3000);
        }

        // 初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 设置Socket连接
            setupSocketConnection();
            
            // 刷新按钮
            document.getElementById('refresh-students')?.addEventListener('click', function() {
                fetchInitialData();
                showNotification('学生数据已刷新', 'success');
            });
            
            // 筛选按钮
            document.querySelectorAll('.filter-btn').forEach(btn => {
                btn.addEventListener('click', function() {
                    // 激活当前按钮
                    document.querySelectorAll('.filter-btn').forEach(b => {
                        b.classList.remove('active');
                    });
                    this.classList.add('active');
                    
                    const filter = this.getAttribute('data-filter');
                    const sections = document.querySelectorAll('.student-section');
                    
                    sections.forEach(section => {
                        section.style.display = 'block';
                    });
                    
                    if (filter === 'tested') {
                        document.getElementById('in-progress-students').style.display = 'none';
                        document.getElementById('not-tested-students').style.display = 'none';
                    } else if (filter === 'in-progress') {
                        document.getElementById('tested-students').style.display = 'none';
                        document.getElementById('not-tested-students').style.display = 'none';
                    } else if (filter === 'not-tested') {
                        document.getElementById('tested-students').style.display = 'none';
                        document.getElementById('in-progress-students').style.display = 'none';
                    }
                });
            });
            
            // 统计卡片点击事件
            document.querySelectorAll('.stat-card').forEach(card => {
                card.addEventListener('click', function() {
                    const target = this.getAttribute('data-scroll');
                    if (target) {
                        // 切换到学生管理标签页
                        document.querySelectorAll('.menu-item').forEach(el => {
                            el.classList.remove('active');
                        });
                        document.querySelector('.menu-item[data-tab="students"]').classList.add('active');
                        
                        document.querySelectorAll('.tab-pane').forEach(pane => {
                            pane.classList.remove('active');
                        });
                        document.getElementById('students').classList.add('active');
                        
                        // 滚动到目标位置
                        setTimeout(() => {
                            const element = document.getElementById(target);
                            if (element) {
                                element.scrollIntoView({ behavior: 'smooth' });
                                element.classList.add('highlight');
                                setTimeout(() => {
                                    element.classList.remove('highlight');
                                }, 2000);
                            }
                        }, 100);
                    }
                });
            });
            
            // 删除学生
            document.getElementById('students')?.addEventListener('click', async function(e) {
                if (e.target.classList.contains('delete-student') || e.target.closest('.delete-student')) {
                    const btn = e.target.closest('.delete-student');
                    const studentId = btn.dataset.id;
                    const studentItem = btn.closest('.student-item');
                    
                    // 确认对话框
                    if (!confirm(`确定要删除学生 ${studentId} 吗？此操作不可撤销。`)) {
                        return;
                    }
                    
                    try {
                        const response = await fetch(`/api/admin/delete/${studentId}`, {
                            method: 'DELETE'
                        });
                        
                        const result = await response.json();
                        
                        if (response.ok) {
                            // 添加删除动画
                            studentItem.classList.add('removed');
                            setTimeout(() => {
                                studentItem.remove();
                                showNotification(`学生 ${studentId} 删除成功！`, 'success');
                            }, 1000);
                        } else {
                            showNotification(`删除失败: ${result.message}`, 'error');
                        }
                    } catch (error) {
                        showNotification(`请求失败: ${error}`, 'error');
                    }
                }
            });
            
            // 监控面板切换
            document.getElementById('connection-status')?.addEventListener('click', function() {
                const panel = document.getElementById('monitor-panel');
                panel.classList.toggle('open');
            });
            
            // 关闭监控面板当点击外部
            document.addEventListener('click', function(event) {
                const panel = document.getElementById('monitor-panel');
                const status = document.getElementById('connection-status');
                
                if (panel.classList.contains('open') && 
                    !panel.contains(event.target) && 
                    !status.contains(event.target)) {
                    panel.classList.remove('open');
                }
            });
            
            // 更新密码表单
            document.getElementById('admin-settings-form')?.addEventListener('submit', async function(e) {
                e.preventDefault();
                
                const formData = new FormData(this);
                const data = {
                    current_password: formData.get('current_password'),
                    new_password: formData.get('new_password'),
                    confirm_password: formData.get('confirm_password')
                };
                
                if (data.new_password !== data.confirm_password) {
                    showNotification('新密码和确认密码不匹配', 'error');
                    return;
                }
                
                try {
                    const response = await fetch('/api/admin/update_password', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify(data)
                    });
                    
                    const result = await response.json();
                    
                    if (response.ok) {
                        showNotification('密码更新成功', 'success');
                        this.reset();
                    } else {
                        showNotification(result.error || '密码更新失败', 'error');
                    }
                } catch (error) {
                    showNotification('请求失败: ' + error.message, 'error');
                }
            });
            
            // 系统设置表单
            document.getElementById('system-settings-form')?.addEventListener('submit', async function(e) {
                e.preventDefault();
                
                const formData = new FormData(this);
                const settings = {
                    system_name: formData.get('system_name'),
                    max_students: parseInt(formData.get('max_students')),
                    data_retention: parseInt(formData.get('data_retention'))
                };
                
                try {
                    const response = await fetch('/api/admin/update_settings', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify(settings)
                    });
                    
                    const result = await response.json();
                    
                    if (response.ok) {
                        showNotification('系统设置已保存', 'success');
                        systemSettings = settings;
                        applySystemSettings();
                    } else {
                        showNotification(result.error || '保存设置失败', 'error');
                    }
                } catch (error) {
                    showNotification('请求失败: ' + error.message, 'error');
                }
            });
        });
    </script>
</body>
</html>